package com.tf_cut.backend.agent.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tf_cut.backend.agent.service.AccountDetailService;
import com.tf_cut.backend.agent.service.AgentAndAccountService;
import com.tf_cut.backend.agent.service.AgentService;
import com.tf_cut.backend.agent.vo.AgentAccountDetailVo;
import com.tf_cut.backend.agent.vo.AgentAndAccountVo;
import com.tf_cut.backend.common.pojo.Result;
import com.tf_cut.backend.type.TradeSubject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/backend/agent/")
public class AgentController {
	@Autowired
	private AccountDetailService detailService;
	
	@Autowired
	private AgentService agentService;
	
	@Autowired
	private AgentAndAccountService agentAndAgentService;
	
	
	
	// 添加代理商
	@RequestMapping("insert")
    public String insertAgentAndAccount(String json) {
		Result<AgentAndAccountVo> result = null;
		AgentAndAccountVo avo = JSON.parseObject(json, AgentAndAccountVo.class);
		try {
			result = agentService.insertAgentAndAccount(avo);
		} catch(Exception e) {
			log.error(e.getMessage(),e);
			result = Result.of(avo);
			result.setMsg(e.getMessage());
			result.setFlag(false);
		}
        return JSON.toJSONString(result);
    }
	
	// 更新代理商基本信息
	@RequestMapping("updateInfo")
    public String updateInfo( String json) {
		Result<AgentAndAccountVo> result = null;
		AgentAndAccountVo avo = JSON.parseObject(json, AgentAndAccountVo.class);
		try {
			result = agentService.updateAgentAndAccount(avo);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result = Result.of(avo);
			result.setMsg(e.getMessage());
			result.setFlag(false);
		}
        return JSON.toJSONString(result);
    }
	
	// 获取代理商
	@RequestMapping("get")
    public String get( String id) {
		AgentAndAccountVo avo = AgentAndAccountVo.builder()
				.agentId(id)
				.build();
		try {
			avo = agentAndAgentService.findListAgentNoPage(avo).get(0);
		}catch(Exception e) {
			log.error("获取代理商异常：get id="+id, e);
		}
		return JSON.toJSONString(avo,SerializerFeature.WriteDateUseDateFormat);
    }
	
	// 冻结（Y）/删除（D）/解冻（N） 代理商
	@RequestMapping("operation")
    public String operation(String id, String state) {
		Result<Boolean> result = Result.of(true);
		result.setFlag(true);
		try {
			AgentAndAccountVo avo = agentService.get(id).getData();
			avo.setAgentState(state);
			agentService.save(avo);
		} catch(Exception e) {
			log.error(e.getMessage(),e);
			result = Result.of(false);
			result.setFlag(false);
		}
		return JSON.toJSONString(result);
    }
	
	// 查找代理商
	@RequestMapping("findListAgent")
	public String findListAgent(String json) {
		AgentAndAccountVo avo = JSON.parseObject(json, AgentAndAccountVo.class);
		return JSON.toJSONString(agentAndAgentService.findListAgent(avo),SerializerFeature.WriteDateUseDateFormat);
	}
	
	// 不分页查找代理商
	@RequestMapping("findListAgentNoPage")
	public String findListAgentNoPage(String json) {
		AgentAndAccountVo avo = JSON.parseObject(json, AgentAndAccountVo.class);
		avo.setAgentState("Y");
		return JSON.toJSONString(agentService.list(avo).getData());
	}
	
	// 代理商加款（1）/扣款（-1）调额
	@RequestMapping("account/operation")
	public String operation(String id, BigDecimal money, Integer direction,String tradeComment) {
		TradeSubject subject = -1 == direction.intValue() 
				? TradeSubject.KOUKUAN : TradeSubject.JIAKUAN;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String endDate = df.format(new Date());
    	String year = endDate.substring(0, 4);
        String month = endDate.substring(5,7);
        String day = endDate.substring(8,10);
        int num = (int)(Math.random()*99+1);
		
		AgentAccountDetailVo aadv = AgentAccountDetailVo.builder()
				.tradeId("JS"+year+month+day+"0000000"+String.valueOf(num))
				.agentAccountId(id)
				.operType(direction)
				.tradeMoney(money)
				.payTime(Timestamp.valueOf(LocalDateTime.now()))
				.paySubject(subject.getCode())
				.payType(subject.getType())
				.isTotal("N")
				.tradeComment(tradeComment)
				.totalTime(Timestamp.valueOf(LocalDateTime.now()))
				.build();
		
		return JSON.toJSONString(detailService.saveOperation(aadv));
	}
	
	// 查找代理商的交易明细
	@RequestMapping("findAgentAccountDetail")
	public String findAgentAccountDetail(String json) {
		AgentAccountDetailVo avo = JSON.parseObject(json, AgentAccountDetailVo.class);
		return JSON.toJSONString(agentAndAgentService.findAgentAccountDetail(avo),SerializerFeature.WriteDateUseDateFormat);
	}

	@RequestMapping("qryUnBindAgent")
	public String qryUnBindAgent(@RequestParam String agentId){
		return JSON.toJSONString(agentAndAgentService.qryUnBindAgent(agentId),SerializerFeature.WriteDateUseDateFormat);
	}

	@RequestMapping("bindAgent")
	public String bindAgent(@RequestParam String agentId,@RequestParam String agentIds){
		List<String> ids = JSON.parseArray(agentIds,String.class);
		return agentAndAgentService.bindAgent(agentId,ids)+"";
	}

	@RequestMapping("unbindAgent")
	public String unbindAgent(@RequestParam String agentId){
		return agentAndAgentService.unBindAgent(agentId)+"";
	}

}
